package com.lsa.letcode.the105.btZigzagTrav;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.lsa.letcode.common.TreeNode;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	private static class Queue extends LinkedList<TreeNode> {
		void addChildren(TreeNode n) {
			if (n.left != null) {
				add(n.left);
			}
			if (n.right != null) {
				add(n.right);
			}
		}
	}
	
	private static class QueueReversed extends Queue {
//		void addChildren(TreeNode n) {
//			if (n.right != null) {
//				add(n.right);
//			}
//			if (n.left != null) {
//				add(n.left);
//			}
//		}

//		@Override
//		public TreeNode poll() {
//			return super.pollLast();
//		}
	}

	public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    	return levelOrder2(root);
    }
    
    /**
     * Using two queue
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder2(TreeNode root) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	if (root == null) {
    		return result;
    	}
    	
    	Queue queue = new Queue();
        Queue queueNext = new QueueReversed();
        queue.add(root);
        
        List<Integer> curLevel = new ArrayList<>();
        while(!queue.isEmpty() || !queueNext.isEmpty()) {
        	if (!queue.isEmpty()) {
        		TreeNode head = queue.poll();
        		curLevel.add(head.val);
        		queueNext.addChildren(head);
        	}
        	else {
        		result.add(curLevel);
        		curLevel = new ArrayList<>();
        		Queue t = queue;
        		queue = queueNext;
        		queueNext = t;
        	}
        }
        result.add(curLevel);
        
        return result;
    }
}